package com.antifake.impl;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

import com.antifake.CodeGenerator;

public class StringCodeGenerator extends CodeGenerator {

	private static final String chars = "abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
	
	private Random rand;
	
	public StringCodeGenerator() {
		rand = new Random(System.currentTimeMillis());
	}
	
	@Override
	public Set generate() {
		Set codeSet = new HashSet(); // 利用Set的无重复特性生成无重复的码，转换成相应的pattern
		while(codeSet.size() < this.getCount()) {
			String randCode = generateOneCode();
			String result = this.getPattern().replace(PLACE_HOLDER, randCode);
			codeSet.add(result);
		}
		return codeSet;
	}
	
	/**
	 * 生成单个随机数。
	 * 利用Random.nextBytes()方法生对应的bytes数组，
	 * 再将每一个byte强制转为int类型将得一个127以内的int类型的值，
	 * 再mod chars的长度取正数，得到相应下标组成一个字符串
	 * @return
	 */
	private String generateOneCode() {
		byte[] bytes = new byte[this.getDigit()];
		char[] codes = new char[this.getDigit()];
		rand.nextBytes(bytes);
		for(int i=0; i<bytes.length; i++) {
			int index = Math.abs(((int) bytes[i]) % chars.length());
			codes[i] = chars.charAt(index);
		}
		return new String(codes);
	}

}
